const { promisify } = require('util')
const figlet = promisify(require('figlet'))
const clear = require('clear')
const chalk = require('chalk')
const open = require('open')
const { clone } = require('./down')
const path = require('path')

/**
 * 封装打印方法
 */
const log = (content) => {
  console.log(chalk.green(content))
}

// 获取当前命令的执行目录，注意和项目目录区分
const cwd = process.cwd()
/**
 * 子进程监控依赖安装，合并到主进程控制台
 */
const spawn = async (...args) => {
  const spawn = require('child_process').spawn(process.platform === "win32" ? "npm.cmd" : "npm", ['install'], {
    stdio: 'inherit',
    cwd: path.join(__dirname, '../')
  })
  // const { spawn } = require('child_process')
  return new Promise((resolve) => {
    const proc = spawn(...args)
    proc.stdout.pipe(process.stdout)
    proc.stderr.pipe(process.stderr)
    proc.on('close', () => {
      resolve()
    })
  })
}

module.exports = async (name) => {
  log('创建项目' + name)
  clear()
  const data = await figlet('welcome chu-cli')
  log(data)
  await clone('github:blue-blue/chu-webpack-template', name)
  log('安装依赖')
  await spawn('npm', ['install'], { cwd: `./${name}` })
  log(
    chalk.green(`
  👌 安装完成:
To get Start:
===========================
cd ${name}

npm run serve
===========================
`)
  )
  // 启动项目
  await spawn('npm', ['run', 'serve'], { cwd: `./${name}` })
  // 打开浏览器
  open('http://localhost:8080')
}
